package com.softeem.ossmusic.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.ossmusic.comm.R;
import com.softeem.ossmusic.entity.Music;
import com.softeem.ossmusic.entity.MusicListDetails;
import com.softeem.ossmusic.service.MusicListDetailsService;
import com.softeem.ossmusic.service.MusicService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name="音乐管理")
@RestController
public class MusicController {

    @Autowired
    private MusicService musicService;
    @Autowired
    private MusicListDetailsService musicListDetailsService;

    @Operation(summary = "音乐列表",description = "分页查询音乐列表")
    @Parameters({
            @Parameter(name = "page",description = "页码"),
            @Parameter(name = "limit",description = "数据条数")
    })
    @GetMapping("/music/list")
    public R list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        //创建分页对象  limit ?,?
        IPage<Music> ipage = new Page<>(page, limit);
        //执行查询(分页)
        List<Music> list = musicService.list(ipage);
        //查询总记录数
        long count =musicService.count();
        //返回结果
        return R.success().setData(list).setCount(count);
    }

    @Operation(summary = "音乐详情",description = "根据id查询音乐详情")
    @Parameters({
            @Parameter(name = "id",description = "音乐id")
    })
    @GetMapping("/music/details")
    public R details(Integer id){
        return musicService.musicDetails(id);
    }

    @Operation(summary = "添加音乐",description = "添加音乐")
    @PostMapping("/music/add")
    public R addMusic(@RequestBody Music music){
        boolean b = musicService.save(music);
        return b ? R.success().setMsg("添加成功") : R.error().setMsg("添加失败");
    }

    @Operation(summary = "删除音乐",description = "根据id删除音乐")
    @Parameters({
            @Parameter(name = "id",description = "音乐id")
    })
    @DeleteMapping("/music/del")
    public R delete(Integer id){
        //组合查询条件
        QueryWrapper<MusicListDetails> query = Wrappers.query(MusicListDetails.class);
        query.eq("music_id", id);
        //根据id查询是否有关联歌单详情数据
        List<MusicListDetails> list = musicListDetailsService.list(query);
        if(list.size() > 0){
            return R.error().setMsg("该音乐有歌单关联，请先解除关联");
        }
        return musicService.removeById(id) ? R.success().setMsg("删除成功") : R.error().setMsg("删除失败");
    }

}
